<!DOCTYPE html>
<html>
	<head>
			<meta charset="utf-8">
			<title></title>
			<style type="text/css">
				
				*{
					margin: 0px;
					padding: 0px;
				}
				
				.moveDiv
				{
					width: 100px;
					height: 100px;
					background-color: red;
					
					position: relative;
					left:0px;
					top:0px;
				}
			</style>
		</head>
		<body>
			<div class="moveDiv">
				
			</div>
			
			
			<script type="text/javascript">
				
				var mouseStartX;
				var mouseStartY;			
				
				var divStartX;
				var divStartY;
				
				var t;
				
				function down(e)
				{
					// e.target事件发生的对象
					if(e.target.className == "moveDiv")
					{
						// 保存正在移动的对象
						t = e.target;
						
						console.log("你点击了红色块")
						
						// 记录鼠标开始的位置
						mouseStartX = e.clientX;
						mouseStartY = e.clientY;
						
						// 记录方块初始位置
						divStartX = e.target.offsetLeft;
						divStartY = e.target.offsetTop;					
						
						// 添加鼠标移动的事件
						document.onmousemove = move;
						// 添加鼠标抬起事件
						document.onmouseup = function(){
							// 移除移动事件
							document.onmousemove = null;
						}
					}
					
				}
				
				function move(e)
				{
					console.log("move"+e.clientX+","+e.clientY);
					// 方块新的位置 = 方块原先的位置+计算鼠标移动的距离
					console.log("移动的对象:"+t);
					t.style.left = divStartX + (e.clientX - mouseStartX)+"px";
					t.style.top = divStartY + (e.clientY - mouseStartY)+"px";
					return false;
				}
				
				document.onmousedown = down;
				
				
			</script>
		</body>
</html>
